package com.user.test.view.fragments.searchResult

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import androidx.fragment.app.Fragment
import android.view.View
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.user.test.R
import com.user.test.databinding.FragmentSearchResultBinding
import com.user.test.viewModel.RetrofitViewModel
import com.user.test.viewModel.RoomViewModel
import com.user.test.viewModel.ViewStateViewModel

class SearchResultFragment: Fragment(R.layout.fragment_search_result) {

    private val retrofitViewModel : RetrofitViewModel by activityViewModels()
    private val roomViewModel: RoomViewModel by activityViewModels()
    private val viewStateViewModel : ViewStateViewModel by activityViewModels()

    private var _binding : FragmentSearchResultBinding? = null
    private val binding get() =  _binding!!



    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSearchResultBinding.inflate(inflater, container, false)
        return binding.root
    }


    @SuppressLint("FragmentLiveDataObserve")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val adapter = SearchResultAdapter(retrofitViewModel.getLink())
        binding.apply {
            rvSearchResult.layoutManager = LinearLayoutManager(context)
            rvSearchResult.adapter = adapter
        }

        roomViewModel.getListSearchResult().observe(this){
            if(it.isNotEmpty()) {
                adapter.addItemList(it)
            }
        }
        viewStateViewModel.getHolderState().observe(this){
            adapter.setHoldersClickable(it)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}